package per.chenxin.tools.foundation;

import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Map;
import java.util.Set;

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.custom.TableEditor;
import org.eclipse.swt.dnd.Clipboard;
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;

import com.swtdesigner.SWTResourceManager;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.events.TraverseListener;
import org.eclipse.swt.events.TraverseEvent;

public class DataShell extends Shell {

    DataShell dataShell;

    private Combo comboSchema;

    ConnectionItem connectionItem;

    Connection connection;

    Statement statement;

    ResultSet resultSet;

    ResultSetData resultSetData;

    Combo comboCatalog;

    public DBTable dbTable;

    List listTable;

    Text textFilter;

    public CTabFolder ctabFolder;

    String strOldFilter;

    Clipboard clipboard;

    ToolItem tltmTime;

    /**
     * Create the shell
     *
     * @param display
     * @param style
     * @throws SQLException
     * @throws ClassNotFoundException
     * @throws IllegalAccessException
     * @throws InstantiationException
     * @throws InvocationTargetException
     * @throws NoSuchMethodException
     * @throws IllegalArgumentException
     * @throws SecurityException
     */
    public DataShell(final Shell shell, int style, ConnectionItem connectionItem)
        throws ClassNotFoundException, SQLException, InstantiationException,
        IllegalAccessException, SecurityException, IllegalArgumentException, NoSuchMethodException,
        InvocationTargetException {

        super(shell, style);
        addTraverseListener(new TraverseListener() {

            public void keyTraversed(TraverseEvent e) {

                if (e.detail == SWT.TRAVERSE_ESCAPE) {
                    e.doit = false;
                }
            }
        });
        this.connectionItem = connectionItem;
        connection = DBUtil.getConnectionFromConnectionItem(connectionItem);
        statement = connection.createStatement();

        clipboard = new Clipboard(shell.getDisplay());

        dbTable = new DBTable(connection);
        createContents();
        addDisposeListener(new DisposeListener() {

            public void widgetDisposed(final DisposeEvent e) {

                closeDB();
                clipboard.dispose();
            }
        });
        setLayout(new FormLayout());
        dataShell = this;
    }

    /**
     * Create contents of the window
     */
    protected void createContents() {

        setText(connectionItem.getUser() + "@" + connectionItem.getURI());
        setSize(600, 450);

        Point pointParentSize = getParent().getSize();
        Point pointParentLocation = getParent().getLocation();
        setLocation(pointParentLocation.x + (pointParentSize.x - getSize().x) / 2,
            pointParentLocation.y + (pointParentSize.y - getSize().y) / 2);

        //

        final Composite compositeLeft = new Composite(this, SWT.BORDER);
        final FormData fd_compositeLeft = new FormData();
        fd_compositeLeft.right = new FormAttachment(0, 200);
        fd_compositeLeft.top = new FormAttachment(0, 0);
        fd_compositeLeft.bottom = new FormAttachment(100, 0);
        fd_compositeLeft.left = new FormAttachment(0, 0);
        compositeLeft.setLayoutData(fd_compositeLeft);
        compositeLeft.setLayout(new FormLayout());

        comboCatalog = new Combo(compositeLeft, SWT.NONE);
        comboCatalog.setFont(SWTResourceManager.getFont("MS UI Gothic", 12, SWT.NORMAL));
        comboCatalog.setVisibleItemCount(10);
        final FormData fd_comboCatalog = new FormData();
        fd_comboCatalog.right = new FormAttachment(100, -1);
        fd_comboCatalog.left = new FormAttachment(0, 0);
        fd_comboCatalog.top = new FormAttachment(0, 0);
        // fd_comboCatalog.bottom = new FormAttachment(0, 20);
        comboCatalog.setLayoutData(fd_comboCatalog);
        comboCatalog.setToolTipText("Catalog");

        comboSchema = new Combo(compositeLeft, SWT.NONE);
        comboSchema.setFont(SWTResourceManager.getFont("MS UI Gothic", 12, SWT.NORMAL));
        comboSchema.setVisibleItemCount(10);
        final FormData fd_comboSchema = new FormData();
        // fd_comboSchema.bottom = new FormAttachment(100, -372);
        fd_comboSchema.right = new FormAttachment(100, -1);
        fd_comboSchema.top = new FormAttachment(comboCatalog, 0);
        fd_comboSchema.left = new FormAttachment(0, 0);
        comboSchema.setLayoutData(fd_comboSchema);
        comboSchema.addSelectionListener(new SelectionAdapter() {

            public void widgetSelected(final SelectionEvent e) {

                setListTable();
            }
        });
        comboSchema.setToolTipText("Schema");

        textFilter = new Text(compositeLeft, SWT.BORDER);
        textFilter.setFont(SWTResourceManager.getFont("MS UI Gothic", 12, SWT.NORMAL));
        textFilter.addKeyListener(new KeyAdapter() {

            @Override
            public void keyPressed(KeyEvent e) {

                if (e.character == '\r') {
                    if (!textFilter.getText().equals(strOldFilter)) {
                        setListTable();
                        strOldFilter = textFilter.getText();
                    }
                }

            }
        });
        textFilter.addFocusListener(new FocusAdapter() {

            @Override
            public void focusGained(FocusEvent e) {

                strOldFilter = textFilter.getText();
            }

            @Override
            public void focusLost(FocusEvent e) {

                if (!textFilter.getText().equals(strOldFilter)) {
                    setListTable();
                    strOldFilter = textFilter.getText();
                }

            }
        });
        textFilter.setToolTipText("regex filter");

        listTable = new List(compositeLeft, SWT.V_SCROLL | SWT.H_SCROLL | SWT.BORDER);
        listTable.setFont(SWTResourceManager.getFont("MS UI Gothic", 12, SWT.NORMAL));
        final FormData fd_listTable = new FormData();
        fd_listTable.top = new FormAttachment(textFilter, 0);
        fd_listTable.bottom = new FormAttachment(100, 0);
        fd_listTable.right = new FormAttachment(100, -1);
        fd_listTable.left = new FormAttachment(0, 0);
        listTable.setLayoutData(fd_listTable);

        listTable.addMouseListener(new MouseAdapter() {

            public void mouseDoubleClick(final MouseEvent e) {

                if (listTable.getItemCount() == 0)
                    return;
                if (listTable.getSelection() == null || listTable.getSelection().length == 0)
                    return;

                String strTablename = listTable.getSelection()[0];
                String strSchema = dbTable.getSchemaFromTable(strTablename);
                if (strSchema != null && strSchema.trim().length() != 0)
                    strTablename = strSchema + "." + strTablename;
                String strSql = "select * from " + strTablename;

                try {
                    DataTabItem dataTabItem = new DataTabItem(dataShell, SWT.CLOSE, connection,
                        strTablename);
                    Table table = dataTabItem.getTable();
                    DBUtil.closeResultSet(resultSet);
                    int intResultCount = DBUtil.getResultCount(statement, strTablename);
                    resultSetData = new ResultSetData(connection, strSql, intResultCount);
                    tltmTime.setText(Long.toString(resultSetData.executeTime) + "ms");
                    dataTabItem.resultSetData = resultSetData;
                    Util.setResultSetTable(table, resultSetData);

                } catch (SQLException e1) {
                    Util.showErrorMessage(ctabFolder.getShell(), "SQLException:" + e1.getMessage());
                    e1.printStackTrace();
                }
            }
        });
        listTable.setDragDetect(false);

        Menu menu = new Menu(listTable);
        listTable.setMenu(menu);

        MenuItem menuItemTableNameCopy = new MenuItem(menu, SWT.NONE);
        menuItemTableNameCopy.addSelectionListener(new SelectionAdapter() {

            @Override
            public void widgetSelected(SelectionEvent e) {

                if (listTable.getSelectionIndex() < 0)
                    return;
                String str = listTable.getItem(listTable.getSelectionIndex());
                TextTransfer textTransfer = TextTransfer.getInstance();

                clipboard.setContents(new String[] {
                    str
                }, new Transfer[] {
                    textTransfer
                });
            }
        });
        menuItemTableNameCopy.setText("&Copy");

        MenuItem menuItemInsert = new MenuItem(menu, SWT.NONE);
        menuItemInsert.addSelectionListener(new SelectionAdapter() {

            @Override
            public void widgetSelected(SelectionEvent e) {

                if (listTable.getSelectionIndex() < 0)
                    return;
                String table = listTable.getItem(listTable.getSelectionIndex());

                String strInsert = DBUtil.createInsertSql(dbTable, table);

                TextTransfer textTransfer = TextTransfer.getInstance();

                clipboard.setContents(new String[] {
                    strInsert
                }, new Transfer[] {
                    textTransfer
                });
            }
        });
        menuItemInsert.setText("&Insert");
        listTable.addKeyListener(new KeyAdapter() {

            public void keyPressed(final KeyEvent e) {

                System.out.println(e.stateMask);

            }
        });

        final FormData fd_textFilter = new FormData();
        fd_textFilter.top = new FormAttachment(comboSchema, 0, SWT.BOTTOM);
        fd_textFilter.right = new FormAttachment(100, -1);
        //fd_text.bottom = new FormAttachment(comboSchema, 15, SWT.BOTTOM);
        fd_textFilter.left = new FormAttachment(0, 0);
        textFilter.setLayoutData(fd_textFilter);

        Composite compositeRight;
        compositeRight = new Composite(this, SWT.NONE);
        compositeRight.setLayout(new FormLayout());

        Composite compositeRightTop = new Composite(compositeRight, SWT.NONE);
        compositeRightTop.setLayout(new FillLayout(SWT.HORIZONTAL));
        FormData fd_compositeRightTop = new FormData();
        fd_compositeRightTop.left = new FormAttachment(0, 10);
        fd_compositeRightTop.right = new FormAttachment(100, -10);
        fd_compositeRightTop.bottom = new FormAttachment(0, 35);
        fd_compositeRightTop.top = new FormAttachment(0, 10);
        compositeRightTop.setLayoutData(fd_compositeRightTop);

        final ToolBar toolBar = new ToolBar(compositeRightTop, SWT.FLAT | SWT.RIGHT);

        tltmTime = new ToolItem(toolBar, SWT.NONE);
        tltmTime.setEnabled(false);

        ToolItem tltmCommit = new ToolItem(toolBar, SWT.NONE);
        tltmCommit.addSelectionListener(new SelectionAdapter() {

            @Override
            public void widgetSelected(SelectionEvent e) {

                try {
                    connection.commit();
                } catch (SQLException e1) {
                    Util.showErrorMessage(toolBar.getShell(), "SQLException:" + e1.getMessage());
                    e1.printStackTrace();
                }

            }
        });
        tltmCommit.setEnabled(!connectionItem.isAutoCommit());

        tltmCommit.setText("Commit");

        ToolItem tltmRollback = new ToolItem(toolBar, SWT.NONE);
        tltmRollback.setEnabled(!connectionItem.isAutoCommit());

        tltmRollback.addSelectionListener(new SelectionAdapter() {

            @Override
            public void widgetSelected(SelectionEvent e) {

                try {
                    connection.rollback();
                } catch (SQLException e1) {
                    Util.showErrorMessage(toolBar.getShell(), "SQLException:" + e1.getMessage());
                    e1.printStackTrace();
                }
            }
        });
        tltmRollback.setText("Rollback");

        ToolItem tltmCreateTab = new ToolItem(toolBar, SWT.NONE);
        tltmCreateTab.addSelectionListener(new SelectionAdapter() {

            @Override
            public void widgetSelected(SelectionEvent e) {

                try {
                    new DataTabItem(dataShell, SWT.CLOSE, connection, "    ");
                } catch (SQLException e1) {
                    Util.showErrorMessage(toolBar.getShell(), "SQLException:" + e1.getMessage());
                    e1.printStackTrace();
                }
            }
        });
        tltmCreateTab.setText("Create Tab");
        final FormData fd_compositeRight = new FormData();
        fd_compositeRight.left = new FormAttachment(compositeLeft, 0);
        fd_compositeRight.right = new FormAttachment(100, 0);
        fd_compositeRight.bottom = new FormAttachment(100, 0);
        fd_compositeRight.top = new FormAttachment(0, 0);
        compositeRight.setLayoutData(fd_compositeRight);

        Composite compositeRightBottom = new Composite(compositeRight, SWT.NONE);
        FormData fd_compositeRightBottom = new FormData();
        fd_compositeRightBottom.top = new FormAttachment(compositeRightTop, 6);
        fd_compositeRightBottom.bottom = new FormAttachment(100, -10);
        fd_compositeRightBottom.left = new FormAttachment(0, 10);
        fd_compositeRightBottom.right = new FormAttachment(100, -10);
        compositeRightBottom.setLayout(new FillLayout(SWT.HORIZONTAL));
        compositeRightBottom.setLayoutData(fd_compositeRightBottom);

        ctabFolder = new CTabFolder(compositeRightBottom, SWT.NONE);

        //        try {
        //            new DataTabItem(ctabFolder, SWT.NONE, connection, "    ");
        //        } catch (SQLException e1) {
        //            Util.showErrorMessage(toolBar.getShell(), "SQLException:" + e1.getMessage());
        //            e1.printStackTrace();
        //        }
        newTabItem(ctabFolder);

        //
        setComboCatalog();
        setComboSchema();
        setListTable();
    }

    @Override
    protected void checkSubclass() {

        // Disable the check that prevents subclassing of SWT components
    }

    private void setComboCatalog() {

        Set<String> set = dbTable.getSetCatalog();
        Object[] objs = set.toArray();
        if (!set.contains(""))
            comboCatalog.add("");
        for (int i = 0; i < objs.length; i++)
            comboCatalog.add((String) objs[i]);
    }

    private void setComboSchema() {

        ArrayList<String> arrayList = new ArrayList<String>();
        arrayList.addAll(dbTable.getSetSchema());
        Collections.sort(arrayList);

        if (!arrayList.contains(""))
            comboSchema.add("");
        for (int i = 0; i < arrayList.size(); i++)
            comboSchema.add((String) arrayList.get(i));
    }

    private void setListTable() {

        listTable.removeAll();
        String strCatalog = comboCatalog.getText();
        String strSchema = comboSchema.getText();
        String strFilter = textFilter.getText();
        Map<String, Map<String, Object>> map = dbTable.getMapTable(strCatalog, strSchema, strFilter);
        ArrayList<String> arrayList = new ArrayList<String>();
        arrayList.addAll(map.keySet());
        Collections.sort(arrayList);
        for (int i = 0; i < arrayList.size(); i++)
            listTable.add(arrayList.get(i));

    }

    private void newTabItem(CTabFolder ctabFolder) {

        CTabItem ctabItem = new CTabItem(ctabFolder, SWT.NONE);

        SashForm sashForm = new SashForm(ctabFolder, SWT.VERTICAL);
        ctabItem.setControl(sashForm);
        ctabItem.setText("        ");

        final StyledText textSql = new StyledText(sashForm, SWT.BORDER | SWT.FULL_SELECTION
            | SWT.WRAP | SWT.V_SCROLL);
        textSql.setFont(SWTResourceManager.getFont("MS UI Gothic", 12, SWT.NORMAL));

        Menu menuText = new Menu(textSql);
        textSql.setMenu(menuText);
        MenuItem menuItemTextCopy = new MenuItem(menuText, SWT.NONE);
        menuItemTextCopy.addSelectionListener(new SelectionAdapter() {

            @Override
            public void widgetSelected(SelectionEvent e) {

                String strSql = textSql.getSelectionText();
                if (strSql.trim().length() == 0)
                    return;
                textSql.copy();
            }
        });
        menuItemTextCopy.setText("&Copy\tCtrl+C");
        menuItemTextCopy.setAccelerator(SWT.CTRL + 'C');

        MenuItem menuItemTextPaste = new MenuItem(menuText, SWT.NONE);
        menuItemTextPaste.addSelectionListener(new SelectionAdapter() {

            @Override
            public void widgetSelected(SelectionEvent e) {

                textSql.paste();
            }
        });
        menuItemTextPaste.setText("&Paste\tCtrl+V");
        menuItemTextPaste.setAccelerator(SWT.CTRL + 'V');

        MenuItem menuItemTextCut = new MenuItem(menuText, SWT.NONE);
        menuItemTextCut.addSelectionListener(new SelectionAdapter() {

            @Override
            public void widgetSelected(SelectionEvent e) {

                textSql.cut();
            }
        });
        menuItemTextCut.setText("Cu&t\tCtrl+X");
        menuItemTextCut.setAccelerator(SWT.CTRL + 'X');

        MenuItem menuItemTextAll = new MenuItem(menuText, SWT.NONE);
        menuItemTextAll.addSelectionListener(new SelectionAdapter() {

            @Override
            public void widgetSelected(SelectionEvent e) {

                textSql.selectAll();
            }
        });
        menuItemTextAll.setText("Select &All\tCtrl+A");
        menuItemTextAll.setAccelerator(SWT.CTRL + 'A');

        final Table table = new Table(sashForm, SWT.FULL_SELECTION | SWT.MULTI | SWT.BORDER
            | SWT.VIRTUAL);

        final TableEditor editor = new TableEditor(table);
        editor.horizontalAlignment = SWT.LEFT;
        editor.grabHorizontal = true;

        table.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseDoubleClick(MouseEvent e) {

                Rectangle clientArea = table.getClientArea();
                Point pt = new Point(e.x, e.y);
                int index = table.getTopIndex();
                while (index < table.getItemCount()) {
                    boolean visible = false;
                    final TableItem item = table.getItem(index);
                    for (int i = 0; i < table.getColumnCount(); i++) {
                        Rectangle rect = item.getBounds(i);
                        if (rect.contains(pt)) {
                            final int column = i;
                            final Text text = new Text(table, SWT.NONE);

                            text.setFont(table.getFont());
                            Listener textListener = new Listener() {

                                public void handleEvent(final Event e) {

                                    switch (e.type) {
                                        case SWT.FocusOut:
                                            item.setText(column, text.getText());
                                            text.setBackground(new Color(text.getDisplay(), 255, 0,
                                                0));
                                            text.dispose();
                                            break;
                                        case SWT.Traverse:
                                            switch (e.detail) {
                                                case SWT.TRAVERSE_RETURN:
                                                    item.setText(column, text.getText());
                                                    text.setBackground(new Color(text.getDisplay(),
                                                        255, 0, 0));
                                                    //FALL THROUGH
                                                case SWT.TRAVERSE_ESCAPE:
                                                    text.dispose();
                                                    e.doit = false;
                                            }
                                            break;
                                    }
                                }
                            };
                            text.addListener(SWT.FocusOut, textListener);
                            text.addListener(SWT.Traverse, textListener);
                            editor.setEditor(text, item, i);
                            text.setText(item.getText(i));
                            text.selectAll();
                            text.setFocus();
                            return;
                        }
                        if (!visible && rect.intersects(clientArea)) {
                            visible = true;
                        }
                    }
                    if (!visible)
                        return;
                    index++;
                }
            }
        });
        table.setFont(SWTResourceManager.getFont("MS UI Gothic", 12, SWT.NORMAL));

        textSql.addKeyListener(new KeyAdapter() {

            public void keyPressed(final KeyEvent e) {

                switch (e.stateMask) {
                    case SWT.CTRL:
                        switch (e.keyCode) {
                            case 'a':
                                textSql.selectAll();
                                break;

                            default:
                                break;
                        }

                        break;
                    case SWT.NONE:

                        switch (e.keyCode) {
                            case SWT.F9:

                                String strSqls = textSql.getSelectionText();
                                if (strSqls.trim().length() == 0)
                                    strSqls = textSql.getText();
                                String[] strsSql = strSqls.split(";");
                                for (String strSql : strsSql) {
                                    if (strSql.trim().length() != 0) {
                                        try {
                                            if (strSql.trim().toLowerCase().startsWith("commit")) {
                                                connection.commit();
                                                Util.showErrorMessage(table.getShell(), "Commit.");
                                            } else if (strSql.trim().toLowerCase().startsWith(
                                                "rollback")) {
                                                connection.rollback();
                                                Util.showErrorMessage(table.getShell(),
                                                    "Rollbacked.");
                                            } else if (strSql.trim().toLowerCase().startsWith(
                                                "select")) {
                                                try {
                                                    resultSetData.finalize();
                                                } catch (Throwable e1) {
                                                }
                                                resultSetData = new ResultSetData(connection,
                                                    strSql);
                                                Util.setResultSetTable(table, resultSetData);
                                            } else {
                                                int intUpdate = DBUtil.executeUpdate(connection,
                                                    strSql);
                                                Util.showErrorMessage(table.getShell(), intUpdate
                                                    + "Updated.");
                                            }
                                        } catch (SQLException e1) {
                                            Util.showErrorMessage(table.getShell(), "SQLException:"
                                                + e1.getMessage());
                                            e1.printStackTrace();
                                        }
                                    }
                                }

                                break;

                            default:
                                break;
                        }

                        break;
                    default:
                        break;
                }

            }
        });

        table.setLinesVisible(true);
        table.setHeaderVisible(true);

        TableColumn tableColumn = new TableColumn(table, SWT.NONE);
        tableColumn.addSelectionListener(new SelectionAdapter() {

            @Override
            public void widgetSelected(SelectionEvent e) {

                System.out.println(e);

            }
        });
        tableColumn.setWidth(100);
        tableColumn.addSelectionListener(new SelectionAdapter() {

            @Override
            public void widgetSelected(SelectionEvent e) {

                TableColumn t = (TableColumn) e.widget;
                table.setSortColumn(t);
                table.setSortDirection(SWT.UP);

            }
        });

        Menu menuTable = new Menu(table);
        table.setMenu(menuTable);

        MenuItem menuItemRecordCopy = new MenuItem(menuTable, SWT.NONE);
        menuItemRecordCopy.addSelectionListener(new SelectionAdapter() {

            @Override
            public void widgetSelected(SelectionEvent e) {

                TableItem[] tableItems = table.getSelection();
                if (tableItems.length == 0)
                    return;

                StringBuffer sb = new StringBuffer();

                for (int j = 0; j < table.getColumnCount(); j++) {
                    sb.append("\"");
                    sb.append(table.getColumn(j).getText());
                    sb.append("\",");
                }
                while (sb.lastIndexOf(",") == sb.length() - 1) {
                    sb.deleteCharAt(sb.length() - 1);
                }
                sb.append("\n");

                for (int i = 0; i < tableItems.length; i++) {
                    for (int j = 0; j < table.getColumnCount(); j++) {
                        sb.append("\"");
                        sb.append(tableItems[i].getText(j));
                        sb.append("\",");
                    }
                    while (sb.lastIndexOf(",") == sb.length() - 1) {
                        sb.deleteCharAt(sb.length() - 1);
                    }
                    sb.append("\n");
                }

                while (sb.lastIndexOf("\n") == sb.length() - 1) {
                    sb.deleteCharAt(sb.length() - 1);
                }

                clipboard.setContents(new Object[] {
                    sb.toString()
                }, new Transfer[] {
                    TextTransfer.getInstance()
                });

            }
        });
        menuItemRecordCopy.setText("&Copy");

        TableItem tableItem = new TableItem(table, SWT.NONE);
        tableItem.addDisposeListener(new DisposeListener() {

            public void widgetDisposed(DisposeEvent e) {

            }
        });
        tableItem.setText("New Item");
        sashForm.setWeights(new int[] {
            98, 290
        });

        ctabFolder.setSelection(ctabItem);
    }

    private void closeDB() {

        DBUtil.closeResultSet(resultSet);
        DBUtil.closeStatement(statement);
        DBUtil.closeConnection(connection);
    }

    @Override
    protected void finalize() throws Throwable {

        closeDB();
        super.finalize();
    }
}
